<template>
  <div class="dashboard-container">
    <div class="app-container">
      <PageTools :show-before="true">
        <span slot="before">共 {{ page.total }} 条记录</span>
        <template slot="after">
          <el-button size="small" type="warning" @click="$router.push('/import')">导入</el-button>
          <el-button size="small" type="danger" @click="exportExcel">导出</el-button>
          <el-button size="small" type="primary" @click="showDialog=true">新增员工</el-button>
        </template>
      </PageTools>

      <el-card>
        <el-table v-loading="isLoading" border :data="list">
          <el-table-column label="序号" sortable="" type="index" />
          <el-table-column label="头像" sortable="" width="220">
            <template #default="{row}">
              <img v-imgerr="require('@/assets/common/head.jpg')" class="avator" :src="row.staffPhoto" alt="" @click="ShowAvator">
            </template>
          </el-table-column>
          <el-table-column label="姓名" sortable="" prop="username" />
          <el-table-column label="工号" sortable="" prop="workNumber" />
          <el-table-column label="聘用形式" sortable="" prop="formOfEmployment" :formatter="formatEmployment" />
          <el-table-column label="部门" sortable="" prop="departmentName" />
          <el-table-column label="入职时间" sortable="">
            <template #default="{row}">
              {{ !row.createTime?'未知时间':$options.filters.formatDate(row.createTime) }}
            </template>
          </el-table-column>
          <el-table-column label="账户状态" sortable="">
            <template #default="{row}">
              <!-- {{ row.enableState }} -->
              <el-switch
                :value="row.enableState===1"
              />
            </template>
          </el-table-column>
          <el-table-column label="操作" sortable="" fixed="right" width="280">
            <template #default="{row}">
              <el-button type="text" size="small" @click="$router.push(`employees/detail/${row.id}`)">查看</el-button>
              <el-button type="text" size="small">转正</el-button>
              <el-button type="text" size="small">调岗</el-button>
              <el-button type="text" size="small">离职</el-button>
              <el-button type="text" size="small" @click="getRolesList(row.id)">角色</el-button>
              <el-button v-if="checkPerm('point-user-delete')" type="text" size="small" @click="delEmployee(row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页组件 -->
        <el-row type="flex" justify="center" align="middle" style="height: 60px">
          <el-pagination
            layout="prev, pager, next"
            :total="page.total"
            :page-size="page.size"
            @current-change="currentChange"
          />
        </el-row>
      </el-card>
      <el-dialog title="头像" :visible="isShowAvator" @close="isShowAvator=false">
        66666
      </el-dialog>
      <AddEmployee :show-dialog.sync="showDialog" />
      <AssignRoles ref="assignRoles" :show-role-dialog.sync="showRoleDialog" :user-id="rolesId" />
    </div>
  </div>
</template>

<script>
// import PageTools from '@/components/PageTools'
import { delEmployee, getEmployeeList } from '@/api/employees'
import EnumEmployee from '@/api/constant/employees'
import AddEmployee from '@/views/employees/components/add-employee.vue'
import PageTools from '@/components/PageTools/index.vue'
import AssignRoles from '@/views/employees/components/assign-role.vue'

export default {
  components: {
    PageTools,
    AddEmployee,
    AssignRoles
  },
  data() {
    return {
      isShowAvator: false,
      rolesId: '',
      showRoleDialog: false,
      showDialog: false,
      isLoading: false,
      list: [],
      page: {
        page: 1,
        size: 5,
        total: 0
      }
    }
  },
  created() {
    this.getEmployeeList()
  },
  methods: {
    checkPerm(pointName) {
      return this.$store.state.user.userInfo.roles.points.includes(pointName)
    },
    // 弹获角色列表，取角色id
    getRolesList(id) {
      this.showRoleDialog = true
      this.rolesId = id
      this.$refs.assignRoles.getRoleDetail(id)
    },
    ShowAvator() {
      this.isShowAvator = true
    },
    async getEmployeeList() {
      this.isLoading = true
      const { rows, total } = await getEmployeeList(this.page)
      // console.log('rows', rows)
      // 假设本地数据库没有 enableState 默认加上
      this.list = rows.map(item => ({
        ...item,
        enableState: item.enableState || 2
        // timeOfEntry: item.timeOfEntry.split('T')[0]
      }))
      this.page.total = total
      // console.log(this.list)
      this.isLoading = false
    },
    currentChange(newPage) {
      // 1 更新页码配置
      this.page.page = newPage
      // 2 发请求
      this.getEmployeeList()
    },
    // 聘用形式
    formatEmployment(row, col, cell, index) {
      const obj = EnumEmployee.hireType.find(item => item.id === cell)
      return obj ? obj.value : '未知形式'
    },
    async exportExcel() {
      // console.log(1)
      const { rows } = await getEmployeeList({ page: 1, size: this.page.total })

      const dict = {
        '手机号': 'mobile',
        '姓名': 'username',
        '入职日期': 'timeOfEntry',
        '聘用形式': 'formOfEmployment',
        '转正日期': 'correctionTime',
        '工号': 'workNumber',
        '部门': 'departmentName'
      }

      const header = Object.keys(dict)
      // console.log(header)

      const newData = rows.map(user => {
        // console.log(user)
        return this.obj2Arr(user, dict)
      })

      console.log(newData)
      // console.log(res)
      const { export_json_to_excel } = await import('@/vendor/Export2Excel.js')
      export_json_to_excel({
        header,
        data: newData
      })
      // export_json_to_excel({
      //   header: ['姓名', '年龄', '性别'],
      //   data: [
      //     ['小明', 3, '男'],
      //     ['小红', 4, '女'],
      //     ['小刚', 6, '男']
      //   ]
      // })
    },
    obj2Arr(user, dict) {
      // console.log(user)
      const res = []
      for (const key in dict) {
        const enkey = dict[key]
        const value = user[enkey]
        // console.log(enkey, value)
        res.push(value)
      }
      return res
    },
    async delEmployee(id) {
      try {
        // 1、提示用户是否删除
        await this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })

        // 2、点击删除，调用接口删除角色信息
        await delEmployee(id)

        // 3、提示删除成功
        this.$message.success('删除成功')

        // 4、页面数据更新
        this.getEmployeeList()
      } catch (error) {
        console.log(error)
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.avator{
  width: 200px;
  height: 130px;
  object-fit: contain;
}
</style>
